<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>项目管理</el-breadcrumb-item>
      <el-breadcrumb-item>项目模板</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="filterName" @input="inputAlter" placeholder="模板名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">
          搜索
        </el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleCreate()">
          新建模板
        </el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="
        dataList.slice(
          (this.pageparm.currentPage - 1) * this.pageparm.pageSize,
          this.pageparm.currentPage * this.pageparm.pageSize
        )
      " highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%">
      <el-table-column sortable prop="name" label="模板名称"> </el-table-column>
      <el-table-column show-overflow-tooltip min-width="128px" prop="config" label="模板配置">
      </el-table-column>
      <el-table-column sortable prop="created" label="创建时间">
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="deleteTmpl(scope.$index, scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 新建页面 -->
    <el-dialog title="新建模板" :visible.sync="createDialogVisible" width="33%" @click="closeCreateDialog">
      <el-form label-width="120px" :model="tmplForm" :rules="tmplRules" ref="tmplForm" class="tmpl-create">
        <el-form-item label="模板名称" prop="name" class="name-input">
          <el-input size="small" v-model="tmplForm.name" auto-complete="off" placeholder="请输入模板名称"></el-input>
        </el-form-item>
        <el-form-item label="模板描述" prop="summary" class="summary-input">
          <el-input size="small" v-model="tmplForm.summary" type="textarea" auto-complete="off" placeholder="请输入模板描述">
          </el-input>
        </el-form-item>
        <el-form-item label="底图服务">
          <el-select v-model="tmplForm.online" placeholder="请选择底图服务" style="display: block" value-key="id">
            <el-option v-for="item in layers.onlines" :key="item.id" :label="item.name" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="影像服务">
          <el-select v-model="tmplForm.raster" placeholder="请选择影像服务" style="display: block" value-key="id">
            <el-option v-for="item in layers.rasters" :key="item.id" :label="item.name" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地形服务">
          <el-select v-model="tmplForm.dem" placeholder="请选择地形服务" style="display: block" value-key="id">
            <el-option v-for="item in layers.terrains" :key="item.id" :label="item.name" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeCreateDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" @click="submitCreate('tmplForm')">
          创建
        </el-button>
      </div>
    </el-dialog>
    <!-- 编辑页面 -->
    <el-dialog title="编辑模板" :visible.sync="editDialogVisible" width="33%" @click="closeEditDialog">
      <el-form label-width="120px" :model="editRow" :rules="editRules" ref="editRow" class="tmpl-edit">
        <el-form-item label="模板名称" prop="name" class="name-input">
          <el-input size="small" v-model="editRow.name" auto-complete="off" placeholder="模板名称"></el-input>
        </el-form-item>
        <el-form-item label="模板描述" prop="summary" class="summary-input">
          <el-input size="small" v-model="editRow.summary" type="textarea" auto-complete="off" placeholder="模板描述">
          </el-input>
        </el-form-item>
        <el-form-item label="模板配置" prop="config" class="config-input">
          <el-input size="small" v-model="editRow.config" type="textarea" rows="5" placeholder="模板配置">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeEditDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" @click="submitEdit('editRow')">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Pagination from "../../components/Pagination";
  import { Base64 } from "js-base64";
  export default {
    data() {
      return {
        loading: false, //是显示加载
        editDialogVisible: false, //控制编辑页面显示与隐藏
        createDialogVisible: false,
        filterName: "",
        tmplForm: {
          name: "",
          summary: "",
          thumbnail: "",
          config: {},
          online: null,
          raster: null,
          dem: null
        },
        editRow: {
          id: "",
          name: "",
          summary: "",
          config: {}
        },
        // rules表单验证
        tmplRules: {
          name: [{ required: true, message: "模板名称不能为空", trigger: "blur" }]
        },
        editRules: {
          name: [{ required: true, message: "模板名称不能为空", trigger: "blur" }]
        },
        dataList: [], //用户数据
        // 分页参数
        pageparm: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        },
        layers: {
          onlines: [],
          rasters: [],
          terrains: []
        },
        czmImg: {
          xbsjGuid: "",
          xbsjType: "Imagery",
          name: "图层",
          xbsjImageryProvider: {
            XbsjImageryProvider: {
              url: "",
              rectangle: [73.5, 18, 135, 54.5]
            }
          }
        },
        czmTerrain: {
          xbsjGuid: "",
          xbsjType: "Terrain",
          name: "地形",
          xbsjTerrainProvider: {
            type: "XbsjCesiumTerrainProvider",
            XbsjCesiumTerrainProvider: {
              url: "",
              requestVertexNormals: true,
              requestWaterMask: true,
              requestMetadata: true,
              rectangle: [73.5, 18, 135, 54.5]
            }
          }
        },
        defaultCfg: {
          sceneTree: {
            root: {}
          },
          cameraViewManager: {
            globe: {
              position: [
                2.1074792836098357,
                0.5522879977522437,
                900.110735832548
              ],
              rotation: [0, -1.5704894508531937, 0],
              near: 0.1,
              far: 10000000000
            },
            china: {
              position: [
                1.8770894704964525,
                0.662547523843314,
                8511735.797037361
              ],
              rotation: [0, -1.5701114159178209, 0],
              near: 0.1,
              far: 10000000000
            },
            lastView: {
              position: [
                1.3649864902516526,
                0.6156734415121061,
                82310.22502608394
              ],
              rotation: [6.196787228680925, -1.5706573060586435, 0],
              fov: 1.0471975511965976,
              near: 0.1,
              far: 10000000000
            }
          }
        }
      };
    },
    // 注册组件
    components: {
      Pagination
    },
    /**
     * 创建完毕
     */
    created() {
      // 获取数据列表
      this.getDataList();
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
      // 获取数据方法
      getDataList() {
        this.$axios
          .get("/templates/")
          .then(res => {
            let resList = res.data.results.list;
            this.dataList = resList.map(item => {
              let tmpl = {};
              tmpl.id = item.id;
              tmpl.name = item.name;
              tmpl.summary = item.summary;
              tmpl.created = item.created_at;
              let cfg = Base64.decode(item.config);
              if (cfg) {
                let cfgV = eval("(" + cfg + ")");
                let jd = JSON.parse(cfgV);
                if (jd && jd.sceneTree && jd.sceneTree.root) {
                  tmpl.config = JSON.stringify(jd.sceneTree.root);
                } else {
                  tmpl.config = "{}";
                }
              }
              return tmpl;
            });
            this.pageparm.total = res.data.results.total;
          })
          .catch(err => {
            this.loading = false;
            this.$message.error("模板加载失败，请稍后再试！");
          });
      },
      getOlmaps() {
        this.$axios.get("/olmaps/").then(res => {
          this.layers.onlines = res.data.results;
        });
      },
      getRasters() {
        this.$axios.get("/rs/").then(res => {
          this.layers.rasters = res.data.results.list;
        });
      },
      getDems() {
        this.$axios.get("/terrains/").then(res => {
          this.layers.terrains = res.data.results.list;
        });
      },
      // 分页插件事件
      callFather(parm) {
        this.pageparm.currentPage = parm.currentPage;
        this.pageparm.pageSize = parm.pageSize;
      },
      //新建页面
      handleCreate: function () {
        this.createDialogVisible = true;
        this.tmplForm.name = "";
        this.tmplForm.summary = "";
        this.tmplForm.online = null;
        this.tmplForm.raster = null;
        this.tmplForm.dem = null;
        // 获取服务列表
        this.getOlmaps();
        this.getRasters();
        this.getDems();
      },
      // 创建页面保存
      submitCreate(formData) {
        this.$refs[formData].validate(valid => {
          if (valid) {
            //use onlines,rasters,terrains create config
            let sceneTreeRoot = {
              children: []
            };
            if (this.tmplForm.online != null) {
              let olmap = this.tmplForm.online;
              let x = JSON.parse(JSON.stringify(this.czmImg)); //复制
              x.name = olmap.name;
              this.tmplForm.thumbnail = olmap.thumbnail;
              let url = olmap.url;
              let prefix = new RegExp("^(http|https)://", "i");
              var match = prefix.test(url);
              if (!match) {
                url = cfg.baseURL + url;
              }
              url += "?access_token=" + cfg.token;
              x.xbsjImageryProvider.XbsjImageryProvider.url = url;
              sceneTreeRoot.children.push({ czmObject: x });
            }
            if (this.tmplForm.raster != null) {
              let rsItem = this.tmplForm.raster;
              let x = JSON.parse(JSON.stringify(this.czmImg));
              x.name = rsItem.name;
              let url = rsItem.url;
              let prefix = new RegExp("^(http|https)://", "i");
              var match = prefix.test(url);
              if (!match) {
                url = cfg.baseURL + url;
              }
              url += "?access_token=" + cfg.token;
              x.xbsjImageryProvider.XbsjImageryProvider.url = url;
              // x.xbsjImageryProvider.XbsjImageryProvider.rectangle ;
              sceneTreeRoot.children.push({ czmObject: x });
            }
            if (this.tmplForm.dem != null) {
              let demItem = this.tmplForm.dem;
              let x = JSON.parse(JSON.stringify(this.czmTerrain));
              x.name = demItem.name;
              let url = demItem.url;
              let prefix = new RegExp("^(http|https)://", "i");
              var match = prefix.test(url);
              if (!match) {
                url = cfg.baseURL + url;
              }
              url += "?access_token=" + cfg.token;
              x.xbsjTerrainProvider.XbsjCesiumTerrainProvider.url = url;
              // x.xbsjImageryProvider.XbsjImageryProvider.rectangle ;
              sceneTreeRoot.children.push({ czmObject: x });
            }
            this.defaultCfg.sceneTree.root = sceneTreeRoot;
            this.tmplForm.config = JSON.stringify(this.defaultCfg);
            this.$axios
              .post("/templates/create/", this.tmplForm)
              .then(res => {
                this.createDialogVisible = false;
                this.loading = false;
                this.getDataList();
              })
              .catch(err => {
                this.createDialogVisible = false;
                this.loading = false;
                this.$message.error("创建新模板失败，请稍后再试！");
              });
          } else {
            return false;
          }
        });
      },
      //显示编辑界面
      handleEdit: function (index, row) {
        this.editDialogVisible = true;
        this.editRow.id = row.id;
        this.editRow.name = row.name;
        this.editRow.summary = row.summary;
        this.editRow.config = row.config;
      },
      // 编辑页面保存
      submitEdit(editData) {
        this.$refs[editData].validate(valid => {
          if (valid) {
            this.loading = true;
            this.defaultCfg.sceneTree.root = JSON.parse(this.editRow.config);
            this.editRow.config = JSON.stringify(this.defaultCfg);
            this.$axios
              .post("/templates/info/" + this.editRow.id + "/", this.editRow)
              .then(res => {
                this.editDialogVisible = false;
                this.loading = false;
                this.getDataList();
              })
              .catch(err => {
                this.editDialogVisible = false;
                this.loading = false;
                this.$message.error("编辑数据提交失败，请稍后再试！");
              });
          } else {
            return false;
          }
        });
      },
      // 删除模板
      deleteTmpl(index, row) {
        this.$confirm("确定要删除吗?", "信息", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.$axios.post("/templates/delete/" + row.id + "/").then(res => {
              this.getDataList();
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      },
      // 关闭新建对话框
      closeCreateDialog() {
        this.createDialogVisible = false;
      },
      // 关闭编辑弹出框
      closeEditDialog() {
        this.editDialogVisible = false;
      },
      // 输入框内容改变
      inputAlter() {
        if (this.filterName == "") {
          this.getDataList();
        } else {
          this.dataList = this.dataList.filter(value => {
            return value.name.match(this.filterName);
          });
          this.pageparm.total = this.dataList.length;
        }
      },
      // 搜索事件
      search() {
        this.dataList = this.dataList.filter(value => {
          return value.name.match(this.filterName);
        });
        this.pageparm.total = this.dataList.length;
      }
    }
  };
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
  }

  .userRole {
    width: 100%;
  }

  .tmpl-create {
    margin-right: 60px;
  }

  .tmpl-edit {
    margin-right: 60px;
  }
</style>